<template>
  <div>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中"
      style="width: 100%;">
      <el-table-column sortable prop="name" label="产品名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="cateName" label="品类" width="100">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="selectProduct(scope.$index, scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
  </div>
</template>

<script>
  import {
    CategoryList,
    ProductList,
  } from '../../api/productApi'
  import Pagination from '../../components/Pagination'
  export default {
    name: 'ProductSelector',
    data() {
      return {
        loading: false, //是显示加载
        categories: [],
        // rules表单验证
        rules: {},
        showUpload: false,
        formInline: {
          page: 1,
          limit: 10,
        },
        listData: [], //用户数据
        // 分页参数
        pageparm: {
          currentPage: 1,
          pageSize: 10,
          total: 10
        }
      }
    },
    // 注册组件
    components: {
      Pagination,
    },
    /**
     * 数据发生改变
     */

    /**
     * 创建完毕
     */
    created() {
      this.getdata(this.formInline)
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
      getdata(parameter) {
        this.loading = true
        CategoryList(parameter).then((res => {
          this.categories = res;
          let cateMap = {};
          this.categories.forEach(c => {
            cateMap[c.id] = c.name;
          });

          ProductList(parameter)
            .then(res => {
              this.loading = false
              res.data.forEach((p => {
                p.cateName = cateMap[p.category];
              }))

              this.listData = res.data
              // 分页赋值
              this.pageparm.currentPage = this.formInline.page
              this.pageparm.pageSize = this.formInline.limit
              this.pageparm.total = res.count

            }, () => {
              this.loading = false
            })
        }))
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.limit = parm.pageSize
        this.getdata(this.formInline)
      },
      // 搜索事件
      search() {
        this.getdata(this.formInline)
      },
      selectProduct(index,row){
        this.$emit('productSelected',row)
      }
    }
  }
</script>